package com.decent.ejfadmin.user.service.impl;

import cn.decent.component.shiro.service.AdminService;
import cn.decent.component.shiro.vo.AdminVO;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.SupCertificateDto;
import com.decent.ejfadmin.common.bean.SupUser;
import com.decent.ejfadmin.common.enums.TriggerTypeEnum;
import com.decent.ejfadmin.common.exception.OperateFailException;
import com.decent.ejfadmin.common.util.WithHoldDes;
import com.decent.ejfadmin.config.PlatConfig;
import com.decent.ejfadmin.user.bean.*;
import com.decent.ejfadmin.user.dao.UserCertificateDao;
import com.decent.ejfadmin.user.service.UserCertificateService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * describe:
 *
 * @author JunLei He
 * @date 2018年10月13日
 */
@Service
@Slf4j
public class UserCertificateServiceImpl implements UserCertificateService {
    @Autowired
    private UserCertificateDao userCertificateDao;
    @Autowired
    private AdminService adminService;
    @Autowired
    private PlatConfig platConfig;

    /**
     * 查询会员实名认证信息
     *
     * @param supUser           会员信息
     * @param page              分页
     * @param supCertificateDto 实名认证信息
     * @return 返回信息
     */
    @Override
    public Page<SupCertificateDto> queryUserCertificateList(SupUser supUser, Page page, SupCertificateDto supCertificateDto) throws Exception {
        PageHelper.startPage(page.getPageNumber(), page.getPageSize());
        List<SupCertificateDto> supCertificateDtos = userCertificateDao.queryUserCertificateList(supUser, supCertificateDto);
        if (Objects.isNull(supCertificateDtos) || supCertificateDtos.isEmpty()) {
            return new Page<>(new ArrayList<>());
        }
        AdminVO currentAdmin = adminService.getCurrentAdmin();
        supCertificateDtos.forEach(t -> {
            String citizenIdNum = WithHoldDes.decodeValue(t.getCitizenIdSalt(), t.getCitizenIdNum());

            // 超级管理员和部门主管可以展示出身份证号码,其他的模糊处理显示前后4位
            if (Const.SUCCESS_CERT.equals(currentAdmin.getRoleId())
                    || (Objects.nonNull(currentAdmin.getSuperAdmin()) && currentAdmin.getSuperAdmin())) {
                t.setCitizenIdNum(citizenIdNum);
            } else {
                //管理平台身份证号码模糊化
                t.setCitizenIdNum(StringUtils.left(citizenIdNum, 4) + StringUtils.repeat("*", StringUtils.length(citizenIdNum) - 8) + StringUtils.right(citizenIdNum, 4));
            }

        });
        return new Page<>(supCertificateDtos);
    }

    /**
     * 查询图片详情
     *
     * @param id id
     * @return
     * @throws Exception
     */
    @Override
    public List<String> queryLevelEsignPic(Long id) throws Exception {
        OssPicUrlBean levelEsignPics = userCertificateDao.queryLevelEsignPic(id);
        if (Objects.isNull(levelEsignPics)) {
            return null;
        }
        //加触发日志
        AdminVO currentAdmin = adminService.getCurrentAdmin();
        SupCertificateLog supCertificateLog = new SupCertificateLog();
        supCertificateLog.setOperatorName(currentAdmin.getName());
        supCertificateLog.setCertificateId(id);
        supCertificateLog.setTriggerType(TriggerTypeEnum.CERT_PICTURE);
        userCertificateDao.insertCertificateLog(supCertificateLog);
        return levelEsignPics.getPicUrlList();
    }

    /**
     * 修改会员实名认证信息
     *
     * @param id     实名认证id
     * @param status 实名认证状态
     * @param remark 备注
     * @return 返回信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public synchronized MessageBean updateUserCertificate(Long id, Integer status, String remark) {
        //获取实名认证信息
        SupCertificateDto supCertificateDto = userCertificateDao.queryUserCertById(id);
        if (Objects.isNull(supCertificateDto)) {
            return MessageBean.fail("认证信息不存在");
        }

        //检测状态
        supCertificateDto.checkCertificateState(status);
        //如果已认证等级是未认证，即第一次认证成功则把支付宝添加到会员支付宝表
        if (Const.LEVEL_ZERO.equals(supCertificateDto.getSuccessLevel())) {
            int insertResult = userCertificateDao.insertAliPay(supCertificateDto.getUserId(), supCertificateDto.getAlipay());
            if (insertResult == 0) {
                log.warn(" 新增会员支付宝记录失败[{}] ", supCertificateDto);
            }
        }
        int i = userCertificateDao.updateUserCertificate(id, status, remark);
        if (i == 0) {
            return MessageBean.fail("操作失败");
        }
		/*
		 * //统计当前的成功金额 int successNum =
		 * userCertificateDao.queryWithdrawSuccessSum(supCertificateDto.getUserId());
		 * //三级审核成功 达到四级 设置4级为认证中 if (successNum >= platConfig.getLevelFour() &&
		 * supCertificateDto.getCertLevel().equals(Const.LEVEL_THREE) &&
		 * Const.SUCCESS_CERT.equals(status)) {
		 * supCertificateDto.setCertLevel(Const.LEVEL_FOUR);
		 * supCertificateDto.setLevelState(Const.CERTING); i =
		 * userCertificateDao.updateUserCertificateState(id, Const.LEVEL_FOUR,
		 * Const.CERTING); if (i == 0) { return MessageBean.fail("操作失败"); } }
		 * //二级三级一起认证,把当前认证等级修改成三级 当前认证状态修改为认证中 if (status.equals(Const.SUCCESS_CERT) &&
		 * supCertificateDto.getCertLevel().equals(Const.LEVEL_TWO) &&
		 * !StringUtils.equalsIgnoreCase(Const.PIC_URL_DEFAULT,
		 * supCertificateDto.getFrontPicUrl())) {
		 * supCertificateDto.setCertLevel(Const.LEVEL_THREE);
		 * supCertificateDto.setLevelState(Const.CERTING); i =
		 * userCertificateDao.updateUserCertificateState(id, Const.LEVEL_THREE,
		 * Const.CERTING); if (i == 0) { return MessageBean.fail("操作失败"); } } //认证状态修改失败
		 * if (Const.FAIL_CERT.equals(status)) { return MessageBean.success(); }
		 * 
		 * //组装实名认证bean SupCertificateRecordDto supCertificateRecordDto = new
		 * SupCertificateRecordDto(supCertificateDto.getUserId(),
		 * supCertificateDto.getCertLevel(), supCertificateDto.getLevelState(),
		 * supCertificateDto.getBizNo());
		 * 
		 * int supCertificateRecord =
		 * userCertificateDao.createSupCertificateRecord(supCertificateRecordDto); if
		 * (supCertificateRecord == 0) { log.info(" 新增支付宝实名认证记录失败[{}] ",
		 * supCertificateRecordDto); throw new OperateFailException("添加认证记录失败"); }
		 */

        return MessageBean.success();
    }

    /**
     * 添加实名认证备注
     *
     * @param id     实名认证id
     * @param remark 备注
     * @return 返回
     * @throws Exception
     */
    @Override
    public MessageBean addRemark(Long id, String remark) throws Exception {
        AdminVO currentAdmin = adminService.getCurrentAdmin();
        String newRemark = currentAdmin.getName() + "增加备注:" + remark;
        if (userCertificateDao.addRemark(id, newRemark) != 1) {
            return MessageBean.fail();
        }
        return MessageBean.success();
    }


}
